package com.example.mybatispermission.controller;

import com.example.mybatispermission.entry.User;
import com.example.mybatispermission.mapper.RoleMapper;
import com.example.mybatispermission.mapper.UserMapper;
import lombok.AllArgsConstructor;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.util.SimpleByteSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;

import java.util.List;

@Controller
@RequestMapping("manager")
@AllArgsConstructor
public class ManagerController {
    private UserMapper userMapper;
    private RoleMapper roleMapper;
    @GetMapping("user")
    @RequiresPermissions("user:select")
    public String userManager(Model model) {
        List<User> users = userMapper.selectList(null);
        model.addAttribute("users", users);
        return "user_manager";
    }
    @GetMapping("user/delete")
    @RequiresPermissions("user:delete")
    public String deleteUser(Integer id){
        userMapper.deleteById(id);
        return "redirect:/manager/user";
    }
    @GetMapping("user/info")
    @RequiresPermissions({"user:select", "role:select"})
    public String getUserInfo(Integer id, Model model) {
        User user = userMapper.selectById(id);
        model.addAttribute("user", user);
        model.addAttribute("roles", roleMapper.selectList(null));
        model.addAttribute("hasRoles", roleMapper.getRolesByUser(user));
        return "user_modify";
    }
    @PostMapping("user/modify")
    @RequiresPermissions("user:update")
    public String modifyUser(User user, @RequestParam List<Integer> roleIds){
        String password = user.getPassword();
        if (StringUtils.isEmptyOrWhitespace(password)) {
            user.setPassword(null);
        } else {
            user.setPasswordSalt(StringUtils.randomAlphanumeric(10));
            Md5Hash hash = new Md5Hash(user.getPassword(), new SimpleByteSource(user.getPasswordSalt()));
            user.setPassword(hash.toHex());
        }
        userMapper.updateById(user);
        userMapper.clearRoles(user);
        userMapper.bindRoles(user, roleMapper.selectBatchIds(roleIds));
        return "redirect:/manager/user";
    }
}
